package murraco.service.impl;

import murraco.common.ResultCode;
import murraco.dto.RecordResponseDto;
import murraco.exception.BusinessException;
import murraco.model.Record;
import murraco.repository.RecordRepository;
import murraco.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RecordServiceImpl implements RecordService {

    private final RecordRepository recordRepository;

    @Autowired
    public RecordServiceImpl(RecordRepository recordRepository) {
        this.recordRepository = recordRepository;
    }

    @Override
    public Record addRecord(String bicycleNum, String pileNum, String userId) {
        Record record = new Record();
        record.setBicycleNum(bicycleNum);
        record.setPileNum(pileNum);
        record.setCreateBy("system");
        record.setUserId(userId);
        record.setCreatedTime(LocalDateTime.now());
        record.setUpdatedTime(LocalDateTime.now());
        record.setBorrowStatus(0);
        return recordRepository.save(record);
    }

    @Override
    public void updateRecord(String id) {
        Record record = recordRepository.findById(id).orElseThrow(() -> new BusinessException(ResultCode.DATA_IS_WRONG));
        LocalDateTime endTime = LocalDateTime.now();
        int minutes = endTime.getMinute() - record.getCreatedTime().getMinute();
        int hours = endTime.getHour() - record.getCreatedTime().getHour();
        int days = endTime.getDayOfYear() - record.getCreatedTime().getDayOfYear();
        int usedTime = days * 24 * 60 + hours * 60 + minutes;
        int useCost = usedTime / 2;
        record.setUpdatedTime(endTime);
        record.setUseCost(useCost);
        record.setUseTime(usedTime);
        record.setBorrowStatus(1);
    }

    @Override
    public List<RecordResponseDto> getRecordListLimit10(String loginCode) {
        return recordRepository.findTop10ByUserIdOrderByUpdatedTimeDesc(loginCode).stream().map(Record::cashToRecordResponseDto).collect(Collectors.toList());
    }
}
